package com.hitqz.robot.biz.controller;

import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.StrUtil;
import com.hitqz.robot.biz.websocket.endpoint.LiveEndpoint;
import com.hitqz.robot.common.core.util.R;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Cleanup;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 推流
 *
 * @author wengyongxin
 * @date 2024-05-26 09:21:06
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/rtsp" )
@Tag(description = "rtsp" , name = "视频流管理" )
@Slf4j
public class RtspController {

	@RequestMapping(value = "/ws" )
	@ResponseBody
	public R receive(HttpServletRequest request){
		String sourceKey = request.getParameter("sourceKey");
		if (StrUtil.isBlank(sourceKey)){
			return R.failed();
		}
		try {
			log.info("开始接收视频流:{}",sourceKey);
			@Cleanup
			InputStream inputStream = request.getInputStream();
			ByteBuffer buffer = ByteBuffer.allocateDirect(4096); // 分配直接缓冲区
			byte[] byteArray = new byte[4096];  // 创建临时字节数组用于读取数据
			int length;
			while (true) {
				length = inputStream.read(byteArray);
				if (length == -1) {
					log.info("流结束");
					break; // 流结束，退出循环
				}
				if (length > 0) {
					buffer.clear();  // 清空缓冲区准备写入数据
					buffer.put(byteArray, 0, length);  // 将数据放入 ByteBuffer
					buffer.flip();  // 切换到读模式
					LiveEndpoint.sendVideoData(sourceKey, buffer);
				}
			}
		}catch (Exception e){
			log.error("推流输出错误",e);
			return R.failed("推流输出错误");
		}
		return R.ok();
	}

}